package com.hserver.statistics.action.api;

import com.google.gson.Gson;
import com.hserver.statistics.bean.DataStatistics;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import top.hserver.core.interfaces.HttpRequest;
import top.hserver.core.interfaces.HttpResponse;
import top.hserver.core.ioc.annotation.Controller;
import top.hserver.core.ioc.annotation.GET;
import com.hserver.statistics.util.FileUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class DownLoadAction {

    /**
     * 下载文件
     *
     * @param response
     * @param request
     */
    @GET("/downLoadFile")
    public void downLoadFile(HttpResponse response, HttpRequest request) {
        String anInterface = request.query("interfaces").trim();
        String module = request.query("module").trim();
        List<String> paths = Arrays.asList(anInterface.split(","));
        String dir = FileUtil.getRunPath() + File.separator + "db" + File.separator + module;
        Gson gson = new Gson();
        // 创建HSSFWorkbook
        XSSFWorkbook wb = new XSSFWorkbook();
        // 添加一个sheet
        XSSFSheet sheet = wb.createSheet("统计");
        // 记录正式数据行数
        int index = 1;
        // 所有统计者
        Map<String, Map<String, Map<String, Object>>> persons = new HashMap<>();
        // 所有
        Map<String, Map<String, Object>> allVx = null;
        // 所有日期
        TreeSet<String> allDate = new TreeSet<>();

        for (String path : paths) {
            allVx = new HashMap<>();
            File origin = new File((dir.trim() + File.separator + path).trim());
            File[] originFiles = origin.listFiles();
            if (originFiles != null) {
                for (File file : originFiles) {
                    try {
                        String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
                        String name = fileName.substring(0, fileName.length() - 8);

                        int i = name.lastIndexOf("-");
                        String vx = name.substring(0, i);
                        String date = fileName.substring(vx.length() + 1);

                        allDate.add(date);

                        if (!allVx.containsKey(vx)) {
                            allVx.put(vx, new HashMap<>());
                        }

                        // 统计所有的数据
                        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
                        String line;
                        int successNum = 0;
                        int errorNum = 0;
                        while ((line = bufferedReader.readLine()) != null && line.length() > 0) {
                            DataStatistics dataStatistics = gson.fromJson(line, DataStatistics.class);
                            successNum += dataStatistics.getSuccessNum();
                            errorNum += dataStatistics.getErrorNum();
                        }
                        bufferedReader.close();
                        allVx.get(vx).put(date, "成功："+successNum+" 失败："+errorNum+" 总数："+(successNum+errorNum));
                    } catch (Exception e) {

                    }
                }
                persons.put(path, allVx);
            }
        }

        // 降序排列时间
        NavigableSet<String> allDates = allDate.descendingSet();

        // 设置表头，即每个列的列名
        Object[] title = Arrays.copyOf(Arrays.asList("一级菜单", "二级菜单").toArray(), allDates.toArray().length + 2);
        System.arraycopy(allDates.toArray(), 0, title, 2, allDates.toArray().length);

        // 创建第一行表头
        XSSFRow row = sheet.createRow(0);

        // 将title写入
        for (int i = 0; i < title.length; i++) {
            // 给列写入数据,创建单元格，写入数据
            row.createCell(i).setCellValue(title[i].toString());
            row.setHeight((short) (row.getHeight() + 20));
        }

        for (Map.Entry<String, Map<String, Map<String, Object>>> map : persons.entrySet()) {
            String name = map.getKey();
            allVx = map.getValue();
            // 新建一行
            row = sheet.createRow(index);
            row.createCell(0).setCellValue(name);
            CellRangeAddress region = new CellRangeAddress(index, index + allVx.size() - 1, 0, 0);
            sheet.addMergedRegion(region);
            for (String vx : allVx.keySet()) {
                for (int i = 0; i < title.length; i++) {
                    // 微信号
                    row.createCell(1).setCellValue(vx);
                    Map<String, Object> dates = allVx.get(vx);
                    // cell 的值
                    if (dates.containsKey(title[i])) {
                        row.createCell(i).setCellValue(dates.get(title[i]).toString());
                    }
                }
                row.setHeight((short) (row.getHeight() + 100));
                index++;
                // 新建一行
                row = sheet.createRow(index);
            }
        }

        for (int i = 0; i < title.length; i++) {
            sheet.autoSizeColumn(i, true);
        }
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            wb.write(baos);
            ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            response.setDownloadFile(swapStream,df.format(new Date())+".xlsx");
        } catch (Exception e) {
            response.sendHtml("下载异常");
        }
    }

}
